import java.io.{File, PrintWriter}
import scala.io.Source
import scala.collection.mutable

object WordFrequencyCounter {
  def main(args: Array[String]): Unit = {
    // 文件路径
    val filePath = "C:\\Users\\PC-608\\Desktop\\2025.txt"
    val outputPath = "C:\\Users\\PC-608\\Desktop\\word.txt"
    try {
      // 读取文件内容
      val content = Source.fromFile(filePath).mkString.toLowerCase

      // 定义正则表达式匹配单词（字母数大于4）
      val wordPattern = "\\b[a-z]{5,}\\b".r

      // 统计词频
      val wordFrequency = mutable.Map[String, Int]().withDefaultValue(0)
      wordPattern.findAllIn(content).foreach { word =>
        wordFrequency(word) += 1
      }

      // 排序并取前300
      val top300 = wordFrequency.toSeq.sortBy(-_._2).take(300)

      // 写入结果文件
      val writer = new PrintWriter(new File(outputPath))
      try {
        writer.println("单词\t词频")
        writer.println("----------------")
        top300.foreach { case (word, count) =>
          writer.println(s"$word\t$count")
        }
        println(s"词频统计完成，结果已保存到: $outputPath")
      } finally {
        writer.close()
      }

    } catch {
      case e: Exception =>
        println(s"发生错误: ${e.getMessage}")
    }
  }
}